package map
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import instance.ActivePolicy;
	import instance.GameModel;
	
	import util.ResourceManager;
	
	import view.AnimatedObject;
	import view.GameObject;
	import view.HeroView;
	import view.KongfuPanda;
	import view.LayerType;
	
	public class ScrollMap extends Sprite
	{
		private var hero:KongfuPanda = new KongfuPanda(ActivePolicy.pandaRun);
		
		public var layers:Object = new Object();
		
		protected static var instance:ScrollMap = null;
		
		static public function get Instance():ScrollMap
		{
			if ( instance == null )
				instance = new ScrollMap();
			return instance;
		}
		
		public function ScrollMap()
		{
			if ( instance != null )
				throw new Error( "Only one Singleton instance should be instantiated" ); 

		}
		
		public function initMap(obj:Object):void {
			this.addChild(layers[LayerType.BACKGROUND] = new ScrollMapLayer(LayerType.BACKGROUND,obj.mapWidth,obj.mapHeight));
			this.addChild(layers[LayerType.NPC] = new ScrollMapLayer(LayerType.NPC,obj.mapWidth,obj.mapHeight));
			this.addChild(layers[LayerType.PLAYER] = new ScrollMapLayer(LayerType.PLAYER,obj.mapWidth,obj.mapHeight));
			this.addChild(layers[LayerType.FRONT] = new ScrollMapLayer(LayerType.FRONT,obj.mapWidth,obj.mapHeight));
		}
		
		public function initHero():void {
			
			if(layers[LayerType.PLAYER]) {
				this.hero.startUpAnimatedObject(ResourceManager.gpandaRun,new Point(100,100),LayerType.PLAYER);
				GameModel.instance.hero = this.hero;
				layers[LayerType.PLAYER].gameObjManager.addBaseObject(this.hero);
			}
			
		}
		
		public function update():void {
			this.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			//重置GameObjectManager的lastTime以保证重新开始后不会跳帧
			reset();
		}
		
		public function pause():void {
			this.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		
		private var lastFrame:Number = new Date().getTime();
		
		public function onEnterFrame(event:Event):void {
			
			if(new Date().getTime() - lastFrame>2000) {
				lastFrame = new Date().getTime();
				var cloud:GameObject = new GameObject(ActivePolicy.cloud);
				cloud.startUpGameObject(ResourceManager.gcloud,new Point(800,Math.random()*480),LayerType.FRONT);
			}
			
			for each(var layer:ScrollMapLayer in layers) {
				layer.enterFrame();
			}
		}
		
		private function reset():void {
			for each(var layer:ScrollMapLayer in layers) {
				layer.gameObjManager.lastFrame = new Date();
			}
		}
	}
}